/* debugger.h
**
** Copyright 2006, Brian Swetland.  All rights reserved.
** See provided LICENSE file or http://frotz.net/LICENSE for details.
*/

#ifndef __DEBUGGER_H__
#define __DEBUGGER_H__

/*
** Public API for implementing debugger commands
*/

#define rd32(addr) (DEBUGIO->_rd32(DEBUGIO, addr))
#define wr32(addr,data) (DEBUGIO->_wr32(DEBUGIO, addr, data))
#define rd32x(addr,data,count) (DEBUGIO->_rd32x(DEBUGIO, addr,data,count))
#define wr32x(addr,data,count) (DEBUGIO->_wr32x(DEBUGIO, addr,data,count))
#define jump_to(addr) (DEBUGIO->_jump_to(DEBUGIO, addr))
#define halt() (DEBUGIO->_halt(DEBUGIO))
#define failed() (DEBUGIO->error != 0)

typedef unsigned Value;
typedef unsigned Address;
typedef const char * String;

Value arg_to_Value(const char *arg);
Address arg_to_Address(const char *arg);
String arg_to_String(const char *arg);

typedef struct 
{
    const char *name;
    void (*func)(int argc, const char **argv);
    const char *help;  
} Command;

/*
** UI related goodies
*/
void msg(const char *fmt, ...);
void ERROR(const char *fmt, ...);
void IOERROR(const char *fmt, ...);

/* fmt codes:
** 'i' int
** 'u' unsigned
** 's' string
** '-' command not found is not an error
*/
int invoke(const char *cmd, const char *fmt, ...);

/*
** DebugIO Transport 
*/

typedef struct DebugIO DebugIO;

struct DebugIO
{
    unsigned (*_rd32)(DebugIO *io, unsigned addr);
    void (*_wr32)(DebugIO *io, unsigned addr, unsigned data);
    void (*_rd32x)(DebugIO *io, unsigned addr, unsigned *data, unsigned count);
    void (*_wr32x)(DebugIO *io, unsigned addr, unsigned *data, unsigned count);
    void (*_jump_to)(DebugIO *io, unsigned addr);
    void (*_halt)(DebugIO *io);

    void (*connect)(DebugIO *io);
    void (*disconnect)(DebugIO *io);
    void (*poll)(DebugIO *io);
    
    const char *name;
    void *ctxt;
    unsigned error;
    unsigned online;
    Command *commands;
};

extern DebugIO *DEBUGIO;

/*
** Internals and bookkeeping
*/

void ui_start(void);
void ui_exit(void);
void ui_addline(const char *line);

#define MAX_ARGS 8

void default_rd32x(DebugIO *io, unsigned addr, unsigned *data, unsigned count);
void default_wr32x(DebugIO *io, unsigned addr, unsigned *data, unsigned count);
void default_jump_to(DebugIO *io, unsigned addr);
void default_halt(DebugIO *io);

void *load_file(const char *name, int *sz);

#endif
